<?php

/**
 * @author chenshubo
 * 推送第三方接口订单
 */
namespace App\Service\OrderService\OrderInterfaceService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\Business;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\SupplierCompany;
use App\Service\AppService\PushOrderSettleMentService;
use App\Service\DeclareService\WayBillDecareService;

class OrderPushSupplier extends BaseService
{
    /**
     * 后台重新推送订单
     * 推送供应商订单接口
     * @param array $param
     */
    public function pushOrder( $param = [] )
    {
        $requestData = $param['requestData'];
        if( empty($requestData['order_id']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order_id");
        }
        
        $order_id = $requestData['order_id'];
        $where = ['id' => $order_id,'order_push_status' => 2];
        $orderInfo = OrderSupplier::instance()->info($where);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单信息不存在");
        }
        
        //售后订单不能再发起推送订单
        if( $orderInfo['after_sale_status'] == 1 ) {
            return Normal::returnCode(Normal::FAIL,"售后订单不能再发起推送订单");
        }
        
        //售后订单不能再发起推送订单
        if( $orderInfo['order_push_status'] == 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前订单已经成功推送给供应商");
        }
        
        //支付信息
        $apply_extends = json_decode($orderInfo['apply_extends'],true);
        $order = [
            'orderSn'               => $orderInfo['order_sn'],
            'paySerial'             => $orderInfo['pay_sn'],
            'payWay'                => $orderInfo['pay_way'],
            'payTime'               => $orderInfo['pay_time'] ? $orderInfo['pay_time'] : time(),
            'payCommanyName'        => $apply_extends['payCommanyName'] ?? '',
            'payCommanyCode'        => $apply_extends['payCommanyCode'] ?? '',
            'enterpriseNum'         => $apply_extends['enterpriseNum'] ?? '',
            'enterpriseName'        => $apply_extends['enterpriseName'] ?? '',
            'innerTransactionId'    => $apply_extends['innerTransactionId'] ?? '',
            'logisticNo'            => $apply_extends['logisticNo'] ?? '',
            'logisticCode'          => $apply_extends['logisticCode'] ?? '',
            'logisticName'          => $apply_extends['logisticName'] ?? '',
            'logisticWayBillContent' => $apply_extends['logisticWayBillContent'] ?? '',
            'idCardFrontImage'      => $apply_extends['idCardFrontImage'] ?? '',
            'idCardBackImage'       => $apply_extends['idCardBackImage'] ?? '',
        ];
        
        $bid = $orderInfo['bid'];
        //获取订单对应商品清单
        $orderGoods = OrderSupplierGoods::instance()->rows(['order_id'=>$order_id,'bid'=>$bid]);
        if( empty($orderGoods) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单商品数据失败");
        }
        
        $binfo = Business::instance()->getUserInfoByBid($bid);
        $company_id = $orderInfo['company_id'];
        $supplierInfo = SupplierCompany::instance()->getSupplierListByIds([$company_id]);
        if( empty($supplierInfo) ) {
            return Normal::returnCode(Normal::FAIL,"供应商信息不存在，请联系管理员核对【{$company_id}】");
        }
        
        $supplierInfo  = current($supplierInfo);
        
        //判断当前是否需要做订单申报,并且是订单申报失败或者未申报的情况
        if( $supplierInfo['OrderDeclare'] == 1 && $orderInfo['is_order_declare'] != 1 && in_array($orderInfo['order_decalre_status'], ['0','3']) ) {
            //需要中台进行订单申报
            return OrderSupplier::instance()->orderPush([//订单申报
                'supplierOrder' => $orderInfo,
                'orderItem'     => $orderGoods,
                'companyInfo'   => $supplierInfo,
                'order'         => $order,
                'binfo'         => $binfo,
            ]);
        }
        
        //此处调用物流公司服务接口
        $result = WayBillDecareService::instance()->upload($binfo, $order,$orderInfo,$orderGoods,$supplierInfo);
        if( $result['code'] != Normal::SUC ) {
            return $result;
        }
        
        //开启写入结算数据事务
        OrderSupplier::instance()->startTrans();
        
        //只需要支付申报的订单，直接推送给到上游供应商， 不需要进行订单进行申报动作
        if ( $orderInfo['is_channel_settlement'] == 1 || $orderInfo['is_supplier_settlement'] ==1 ){
            $param = [
                'supplierOrder' => $orderInfo,
                'binfo'         => $binfo,
                'mode'          => PushOrderSettleMentService::SETTLEMENT_MODE_PAY
            ];
            $res = PushOrderSettleMentService::instance()->addOrderSettleMentLog($param);
            if( $res['code'] != Normal::SUC ) {
                OrderSupplier::instance()->rollback();
                return $res;
            }
        }
        
        $res = $this->pushSupplierOrder([
            'companyInfo'   => $supplierInfo,
            'supplierOrder' => $orderInfo,
            'orderItem'     => $orderGoods,
            'order'         => $order,
            'binfo'         => $binfo
        ]);
        
        //推送成功,提交事务
        if( $res['code'] == Normal::SUC ) {
            OrderSupplier::instance()->commit();
            return $res;
        }
        
        OrderSupplier::instance()->rollback();
        return $res;
    }
    
    /**
     * 向供应商推送订单数据
     * @param array $param
     */
    public function pushSupplierOrder( $param = [] ) 
    {
        if( empty($param['companyInfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param companyInfo");
        }
        if( empty($param['supplierOrder']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder");
        }
        if( empty($param['orderItem']) ) {
            return Normal::returnCode(Normal::FAIL,"except param orderGoods");
        }
        if( empty($param['order']) ) {
            return Normal::returnCode(Normal::FAIL,"except param order");
        }
        if( empty($param['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param binfo");
        }
        
        $supplierInfo = $param['companyInfo'];
        $orderInfo    = $param['supplierOrder'];
        $orderGoods   = $param['orderItem'];
        $order        = $param['order'];
        $binfo        = $param['binfo'];
        $param['apiBody'] = $supplierInfo['apiBody'];
        
        //找到指定供应商路由
        $supplierCode  = $supplierInfo['OrderDockMode'] == 0 ? $supplierInfo['company_code'] : 'Normal';
        $supplierCode  = ucfirst($supplierCode);
        $serviceClass  = "App\\Service\\OrderService\\OrderRouteService\\{$supplierCode}";
        if( !class_exists($serviceClass) ) {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} not existed");
        }
        
        $requestMethod = 'orderPay';
        if( !method_exists($serviceClass,$requestMethod) ) {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} {$requestMethod} methods not existed");
        }
        
        try {
            $res = $serviceClass::instance()->$requestMethod([
                'companyInfo'   => $supplierInfo,
                'supplierOrder' => $orderInfo,
                'orderGoods'    => $orderGoods,
                'order'         => $order,
                'binfo'         => $binfo,
                'apiBody'       => $supplierInfo['apiBody']
            ]);
        }
        catch ( \Throwable $th )
        {
            $res = Normal::returnCode(Normal::FAIL,"调用系统路由失败[{$th->getMessage()}]");
        }
        
        //支付公司和支付电商平台信息
        $apply_extends = json_encode($order,JSON_UNESCAPED_UNICODE);
        
        //推送成功
        $where = ['id' => $orderInfo['id'],'bid'=>$orderInfo['bid']];
        if( $res['code'] == Normal::SUC ) {
            $data = [
                'order_push_status' => 1 ,
                'order_push_remark' => $res['msg'],
                'order_push_time'   => time(),
                'order_push_result' => $res['msg'],
                'apply_extends'     => $apply_extends
            ];
            //更新第三方订单号
            if( isset($res['data']['thirdpart_order_sn']) && !empty($res['data']['thirdpart_order_sn'])) {
                $data['thirdpart_order_sn'] = $res['data']['thirdpart_order_sn'];
            }
            
        } else {
            $data = [
                'order_push_status' => 2 ,
                'order_push_remark' => $res['msg'],
                'order_push_time'   => time(),
                'order_push_result' => $res['msg'],
                'apply_extends'     => $apply_extends
            ];
        }
        
        OrderSupplier::instance()->edit($where,$data);
        return $res;
    }
}